export default {
  namespaced: true,
  state: {
    carts: [],
  },
  getters: {
    total(state) {
      // return state.carts
      return state.carts
        .reduce((total, item) => {
          return (total += item.count * item.price);
        }, 0)
        .toFixed(2);
    },
  },
  mutations: {
    SET_CARTS(state, payload) {
      // state.carts = payload
      //判断cats里是否有该商品
      // 如果有 数量+1
      //如果没有 添加进carts
      let target = state.carts.find((item) => item.id === payload.id);
      if (target) {
        target.count++;
      } else {
        let obj = {
          // inventory: payload.inventory,
          title: payload.title,
          id: payload.id,
          count: 1,
          price: payload.price,
        };
        state.carts.push(obj);
      }
    },
    //移出购物车
    REMOVE_CART(state, payload) {
      payload.count--;
      console.log(payload);
      if (payload.count === 0) {
        state.carts = state.carts.filter((item) => item.id !== payload.id);
      }
    },
  },
  actions: {},
  modules: {},
};
